<template>
  <div style="padding-left: 10px; padding-top: 20px">
    <el-container style="height: 100%; border: 1px solid #eee">
      <el-aside
        width="200px"
        style="overflow: hidden; height: calc(100vh - 80px)"
      >
        <div>
          <el-input
            placeholder="请输入内容"
            v-model="keyword"
            class="input-with-select"
            clearable
            size="small"
          >
          </el-input>
        </div>
        <div style="height: calc(100vh - 130px); overflow-y: auto">
          <el-tree
            ref="accountTree"
            :data="accounts"
            :props="accountProps"
            node-key="id"
            default-expand-all
            highlight-current
            :expand-on-click-node="false"
            :filter-node-method="filterNode"
            @current-change="handleNodeChange"
          ></el-tree>
        </div>
      </el-aside>
      <el-main>
        <div>
          <toolbar
            :table="$refs.xTable"
            :buttons.sync="displayButtons"
            @add="handleAddNew"
            @delete="handleDelete"
            @refresh="handleRefresh"
            @submit="handleSubmit"
            @back="handleReturnList"
          >
          </toolbar>
        </div>
        <div style="margin-top: 10px">
          <vxe-table
            border
            align="center"
            show-footer
            :data="balances"
            auto-resize
            :export-config="{}"
            resizable
            ref="xTable"
            :show-overflow="false"
            @cell-click="handleCellClick"
            size="small"
            :rules="getRules()"
            :mouse-config="{ selected: true }"
            :checkbox-config="{ range: true }"
            :keyboard-config="{
              isArrow: true,
              isDel: false,
              isEnter: true,
              isTab: true,
              isEdit: true,
            }"
            :edit-config="{
              trigger: 'click',
              mode: 'cell',
              activeMethod: handleCellEnableEdit,
            }"
            :footer-method="handleFooterData"
          >
            <vxe-table-column type="checkbox" width="60"></vxe-table-column>

            <vxe-table-column
              field="currencyId"
              title="货币"
              align="center"
              header-align="center"
              width="180"
              :edit-render="{
                attrs: {},
                autofocus: '.custom-input',
              }"
            >
              <template #default="{ row }">
                <div>
                  {{ row.currencyCode }}
                </div>
              </template>
              <template #edit="{ row }">
                <currency-select
                  v-model="row.currencyId"
                  optionClass="vxe-table–ignore-clear"
                  @change="(item) => handleCurrencyChange(row, item)"
                ></currency-select>
              </template>
            </vxe-table-column>
            <vxe-table-column
              field="dimensionGroupValueId"
              title="核算维度"
              align="left"
              header-align="center"
              :visible="
                currentAccount &&
                currentAccount.dimensionItems &&
                currentAccount.dimensionItems.length > 0
              "
              :edit-render="{
                enabled: true,
                autoselect: true,
              }"
            >
              <template #default="{ row }">
                <dimension-value-panel
                  :dimensionItems.sync="currentAccount.dimensionItems"
                  :dimensionItemValues.sync="row.dimensionGroupValueItems"
                ></dimension-value-panel>
              </template>
              <template #edit="{ row }">
                <dimension-value-select
                  :dimensionItems="currentAccount.dimensionItems"
                  :dimensionItemValues="row.dimensionGroupValueItems"
                  v-model="row.dimensionGroupValueId"
                  optionClass="vxe-table–ignore-clear"
                  @change="(values) => handleDimensionValueChange(row, values)"
                ></dimension-value-select>
              </template>
            </vxe-table-column>
            <vxe-table-colgroup field="group1" title="期初余额">
              <vxe-table-column
                field="openingAmountFr"
                title="原币"
                align="right"
                header-align="center"
                :edit-render="{
                  attrs: {},
                }"
              >
                <template #default="{ row }">
                  <div>
                    <span>{{ row.openingAmountFr | money }}</span>
                  </div>
                </template>
                <template #edit="{ row }">
                  <number-input
                    v-model="row.openingAmountFr"
                    :precision="2"
                    @input="
                      (value) => handleAmountInput(row, value, 'openingAmount')
                    "
                  ></number-input>
                </template>
              </vxe-table-column>
              <vxe-table-column
                field="openingAmount"
                title="本位币"
                align="right"
                header-align="center"
                :edit-render="{
                  attrs: {},
                }"
              >
                <template #default="{ row }">
                  <span>{{ row.openingAmount | money }}</span>
                </template>
                <template #edit="{ row }">
                  <number-input
                    v-model="row.openingAmount"
                    :precision="2"
                  ></number-input>
                </template>
              </vxe-table-column>
            </vxe-table-colgroup>
            <vxe-table-colgroup field="group2" title="本年累计借方">
              <vxe-table-column
                field="currentYearDebitAmountFr"
                title="原币"
                align="right"
                header-align="center"
                :edit-render="{
                  attrs: {},
                }"
              >
                <template #default="{ row }">
                  <div>
                    <span>{{ row.currentYearDebitAmountFr | money }}</span>
                  </div>
                </template>
                <template #edit="{ row }">
                  <number-input
                    v-model="row.currentYearDebitAmountFr"
                    :precision="2"
                    @input="
                      (value) =>
                        handleAmountInput(row, value, 'currentYearDebitAmount')
                    "
                  ></number-input>
                </template>
              </vxe-table-column>
              <vxe-table-column
                field="currentYearDebitAmount"
                title="本位币"
                align="right"
                header-align="center"
                :edit-render="{
                  attrs: {},
                }"
              >
                <template #default="{ row }">
                  <div>
                    <span>{{ row.currentYearDebitAmount | money }}</span>
                  </div>
                </template>
                <template #edit="{ row }">
                  <number-input
                    v-model="row.currentYearDebitAmount"
                    :precision="2"
                  ></number-input>
                </template>
              </vxe-table-column>
            </vxe-table-colgroup>
            <vxe-table-colgroup field="group3" title="本年累计贷方">
              <vxe-table-column
                field="currentYearCreditAmountFr"
                title="原币"
                align="right"
                header-align="center"
                :edit-render="{
                  attrs: {},
                }"
              >
                <template #default="{ row }">
                  <div>
                    <span>{{ row.currentYearCreditAmountFr | money }}</span>
                  </div>
                </template>
                <template #edit="{ row }">
                  <number-input
                    v-model="row.currentYearCreditAmountFr"
                    :precision="2"
                    @input="
                      (value) =>
                        handleAmountInput(row, value, 'currentYearCreditAmount')
                    "
                  ></number-input>
                </template>
              </vxe-table-column>
              <vxe-table-column
                field="currentYearCreditAmount"
                title="本位币"
                align="right"
                header-align="center"
                :edit-render="{
                  attrs: {},
                }"
              >
                <template #default="{ row }">
                  <div>
                    <span>{{ row.currentYearCreditAmount | money }}</span>
                  </div>
                </template>
                <template #edit="{ row }">
                  <number-input
                    v-model="row.currentYearCreditAmount"
                    :precision="2"
                  ></number-input>
                </template>
              </vxe-table-column>
            </vxe-table-colgroup>
            <template #empty v-if="!readonly">
              <p v-if="readonly">暂无数据</p>
              <el-link v-if="!readonly" @click="handleAddNew" type="primary"
                >新增一行
              </el-link>
            </template>
          </vxe-table>
        </div>
      </el-main>
    </el-container>
  </div>
</template>
<script>
import { getAccounts } from "@/api/account";
import {
  getAccountInitalizations,
  addAccountInitalizations,
  updateAccountInitalizations,
  deleteAccountBalance,
} from "@/api/accountBalance";
import toolbar from "@/components/Bar/toolbar.vue";
import currencySelect from "@/components/Select/currencySelect.vue";
import numberInput from "@/components/Input/numberInput.vue";
import dimensionValueSelect from "@/components/Select/dimensionValueSelect.vue";
import dimensionValuePanel from "@/components/Panel/dimensionValuePanel.vue";
import "@/utils/filters";
export default {
  components: {
    toolbar,
    currencySelect,
    numberInput,
    dimensionValueSelect,
    dimensionValuePanel,
  },
  data() {
    return {
      accounts: [],
      balances: [],
      accountProps: {
        children: "children",
        label: "fullName",
      },
      keyword: "",
      headTitle: "",
      currentAccount: null,
      isModifying: false,
    };
  },
  methods: {
    getAccounts() {
      getAccounts({ includeDetail: true }).then((res) => {
        res = res || [];
        res.forEach((account) => {
          account.fullName = account.code + " " + account.name;
        });
        this.accounts = res.toTree();

        if (this.accounts.length == 0) return;

        let accountId = this.$route.query.accountId || this.accounts[0].id;
        this.$nextTick(() => {
          this.$refs.accountTree.setCurrentKey(accountId);
          this.currentAccount = this.$refs.accountTree.getCurrentNode();
        });
      });
    },
    getBalances() {
      getAccountInitalizations(this.currentAccount.id).then((res) => {
        res = res ? res.items || [] : [];
        //子级科目过滤掉没有币别和核算维度的项，父级科目过滤没有币别的
        res = this.currentAccount.isLeaf
          ? res.filter((x) => {
              return !!x.currencyId && !!x.dimensionGroupValueId;
            })
          : res.filter((x) => {
              return !!x.currencyId;
            });

        this.balances = res || [];
        this.isModifying = false;
      });
    },
    handleNodeChange(data) {
      if (this.isModifying) {
        this.$confirm("当前数据为保存，是否切换科目?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
          .then(() => {
            this.switchAccount(data);
          })
          .catch(() => {
            this.$refs.accountTree.setCurrentKey(this.currentAccount.id);
          });
      } else {
        this.switchAccount(data);
      }
    },
    switchAccount(data) {
      this.headTitle =
        data.fullName + " [" + (data.direction == 1 ? "借" : "贷") + "]";
      this.currentAccount = data;
      this.isModifying = false;
    },
    filterNode(value, data) {
      if (!value) return true;
      return data.fullName.indexOf(value) !== -1;
    },
    getRules() {
      var rules = {
        currencyId: [{ required: true, message: "币别为必填项" }],
      };
      return rules;
    },
    handleRefresh() {
      this.getBalances();
    },
    handleReturnList() {
      if (this.isModifying) {
        this.$confirm("当前数据为保存，是返回列表?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
          .then(() => {
            this.$router.push({
              name: "OpeningBalance",
            });
          })
          .catch(() => {});
      } else {
        this.$router.push({
          name: "OpeningBalance",
        });
      }
    },
    handleAddNew() {
      let balance = this.defaultBalance();

      this.$refs.xTable.insertAt(balance, -1);
      this.balances.push(balance);
    },
    handleDelete({ ids, rows }) {
      if (!rows || rows.length == 0) return;
      for (let i = 0; i < rows.length; i++) {
        let row = rows[i];
        if (row.id) {
          deleteAccountBalance(row.id).then((res) => {
            if (!res) return;
            if (i == rows.length - 1) {
              this.$notify({
                title: "成功",
                message: "删除成功",
                type: "success",
                position: "bottom-right",
              });
              this.getBalances();
            }
          });
        } else {
          this.$refs.xTable.remove(row);
          this.balances.remove(row);
        }
      }
    },
    handleCurrencyChange(row, item) {
      row.currencyCode = item.code;
    },
    handleCellClick({ row, rowIndex }) {},
    handleCellEnableEdit({ row, rowIndex, column, columnIndex }) {
      if (
        !this.currentAccount.isForeignCurrency &&
        [
          "currencyId",
          "openingAmount",
          "currentYearDebitAmount",
          "currentYearCreditAmount",
        ].includes(column.property)
      ) {
        return false;
      }

      let result = column.property == "currencyId" || !!row.currencyId;

      if (result) this.isModifying = true;
      return result;
    },
    handleAmountInput(row, value, property) {
      if (!property) return;
      if (!this.currentAccount.isForeignCurrency) {
        property;
        row[property] = value;
      }
    },
    defaultBalance() {
      let balance = {
        period: this.getPeriod(),
        currencyId: "",
        currencyCode: "",
        openingAmount: "",
        openingAmountFr: "",
        dimensionGroupValueId: "",
        dimensionGroupValueItems: [],
        currentYearDebitAmount: "",
        currentYearDebitAmountFr: "",
        currentYearCreditAmount: "",
        currentYearCreditAmountFr: "",
      };

      if (!this.currentAccount.isForeignCurrency) {
        balance.currencyId = this.org.currencyId;
        balance.currencyCode = this.org.currencyCode;
      }

      return balance;
    },
    handleSubmit() {
      if (!this.balances || this.balances.length == 0) {
        this.$notify.error({
          title: "错误",
          message: "没有需要保存的数据",
          position: "bottom-right",
        });
        return;
      }

      let data = {
        accountId: this.currentAccount.id,
        isInitalization: true,
        period: this.getPeriod(),
        items: this.balances,
      };

      updateAccountInitalizations(data).then((res) => {
        if (!res) return;
        this.$notify({
          title: "成功",
          message: "保存成功",
          type: "success",
          position: "bottom-right",
        });
        this.getBalances();
      });
    },
    getPeriod() {
      let activationDate = this.org.activationDate;

      if (!activationDate) return 0;
      activationDate = new Date(activationDate);
      return activationDate.getFullYear() * 100 + activationDate.getMonth();
    },
    handleFooterData({ columns, data }) {
      let result = [];
      //按照币别进行一次分组
      let currencyGroups = [];

      data.forEach((row) => {
        let currencyCode = row.currencyCode;

        if (currencyCode) {
          let match = currencyGroups.find((x) => {
            return x.currencyCode == currencyCode;
          });

          if (!match) {
            match = { currencyCode: row.currencyCode, rows: [] };
            currencyGroups.push(match);
          }

          match.rows.push(row);
        }
      });
      //每个币别的合计
      for (let i = 0; i < currencyGroups.length; i++) {
        let currencyGroupItem = currencyGroups[i];

        let currencyTotalRow = columns.map((column, _columnIndex) => {
          if (_columnIndex === 0) return "合计";
          if (["currencyId"].includes(column.property))
            return currencyGroupItem.currencyCode;

          if (["dimensionValueGroupId"].includes(column.property)) return "";

          return this.calculateAmount(currencyGroupItem.rows, column.property);
        });

        result.push(currencyTotalRow);
      }

      //综合本位币
      let totalRow = columns.map((column, _columnIndex) => {
        if (_columnIndex === 0) {
          return "";
        }

        if (["currencyId"].includes(column.property)) {
          return "综合本位币（" + this.org.currencyCode + "）";
        }
        if (
          [
            "openingAmountFr",
            "currentYearDebitAmountFr",
            "currentYearCreditAmountFr",
            "dimensionValueGroupId",
          ].includes(column.property)
        ) {
          return "";
        }

        return this.calculateAmount(data, column.property);
      });

      result.push(totalRow);

      return result;
    },
    calculateAmount: function (list, field) {
      let count = 0.0;
      list.forEach((item) => {
        count = count + +item[field];
      });
      return count == 0 ? "" : count.toMoney();
    },
    handleDimensionValueChange(row, values) {
      if (!values || values.length == 0) {
        row.dimensionGroupValueItems = [];
        return;
      }
      for (let i = 0; i < values.length; i++) {
        let value = values[i];
        let match = row.dimensionGroupValueItems.find((x) => {
          return (
            x.dataSourceType == value.dimension.dataSourceType &&
            (!value.tag || x.tagId == value.tag.id)
          );
        });

        if (match) {
          match.value = value.value;
          match.label = value.label;
        } else {
          row.dimensionGroupValueItems.push({
            dataSourceType: value.dimension.dataSourceType,
            tagId: value.tag ? value.tag.id : null,
            value: value.value,
            label: value.label,
          });
        }
      }
    },
  },
  mounted() {
    this.getAccounts();
  },
  watch: {
    keyword(value) {
      this.$refs.accountTree.filter(value);
    },
    currentAccount(value) {
      if (!value) {
        this.balances = [];
        this.headTitle = "";
      } else {
        this.headTitle =
          value.fullName + " [" + (value.direction == 1 ? "借" : "贷") + "]";
        this.getBalances();
      }
      this.$nextTick(() => {
        this.$refs.xTable.refreshColumn();
      });
    },
  },
  computed: {
    org() {
      return this.$store.state.organization.data;
    },
    readonly() {
      return (
        !this.currentAccount ||
        !this.currentAccount.children ||
        this.currentAccount.children.length > 0
      );
    },
    displayButtons() {
      return this.readonly ? ["back"] : ["add", "delete", "submit", "back"];
    },
  },
  props: {},
};
</script>
<style scoped></style>
